package com.marry.daodao.authserver.infrastructure.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Sets;
import com.marry.daodao.authserver.domain.User;
import com.marry.daodao.authserver.infrastructure.dao.entity.MlUser;
import com.marry.daodao.authserver.infrastructure.dao.entity.MlUserRole;
import com.marry.daodao.authserver.infrastructure.dao.mapper.UserEntityMapper;
import com.marry.daodao.authserver.infrastructure.dao.mapper.UserRoleMapper;
import com.marry.daodao.authserver.infrastructure.repository.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author mal
 * @date 2022-11-15 11:48
 */
@Repository
@AllArgsConstructor
public class UserRepositoryImpl implements UserRepository {

    private final UserEntityMapper userEntityMapper;

    private final UserRoleMapper userRoleMapper;



    @Override
    public User findByUsername(String username) {
        MlUser userEntity = userEntityMapper.selectOne(new QueryWrapper<MlUser>().lambda().eq(MlUser::getUsername, username));
        if (userEntity == null) {
            return null;

        }

        User user = new User();
        user.setUserId(userEntity.getId());
        user.setUsername(userEntity.getUsername());
        user.setPassword(userEntity.getPassword());
        user.setCanceled("S".equals(userEntity.getState()));
        user.setLocked("C".equals(userEntity.getState()));
        user.setActive((userEntity.getEffStartDate() == null && userEntity.getEffEndDate() == null)
                || (userEntity.getEffStartDate().isBefore(LocalDateTime.now())) && userEntity.getEffEndDate().isAfter(LocalDateTime.now()));

        Set<String> authorities = Sets.newHashSet();

        List<MlUserRole> mlUserRoles = userRoleMapper.selectList(new QueryWrapper<MlUserRole>().lambda().eq(MlUserRole::getUserId, userEntity.getId()).eq(MlUserRole::getState, "1"));
        authorities.addAll(mlUserRoles.stream().map(MlUserRole::getRoleId).collect(Collectors.toList()));

        if (!CollectionUtils.isEmpty(authorities)) {
            user.setAuthorities(authorities.parallelStream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));

        }


        return user;
    }

    @Override
    public User findById(Long userId) {
        return null;
    }
}
